package ntd.util.frame.action.function.video.tool;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;
import com.dahuatech.hutool.http.Method;
import com.dahuatech.icc.exception.ClientException;
import com.dahuatech.icc.oauth.http.DefaultClient;
import com.dahuatech.icc.oauth.model.v202010.GeneralRequest;
import com.dahuatech.icc.oauth.model.v202010.GeneralResponse;
import ntd.util.UtilCatch;
import ntd.util.config.common.enums.protocol.EnumStreamUrlProtocol;
import ntd.util.config.common.exception.ComException;
import ntd.util.frame.action.function.video.bo.ActionVideoInBo;
import ntd.util.frame.javacv.dahua.DeviceBean;
import ntd.util.frame.javacv.dahua.DeviceChannelBean;
import ntd.util.frame.javacv.dahua.Result;

import java.util.List;

public class ToolDaHua {

    private DefaultClient defaultClient;

    public ToolDaHua(DefaultClient defaultClient) {
        this.defaultClient = defaultClient;
    }

    public String getUrl(ActionVideoInBo actionVideoInBo) {
        return UtilCatch.tryCatch(() -> {
            GeneralRequest generalRequest = generatorRequest(actionVideoInBo);

            generalRequest.body(configParams(actionVideoInBo).toString());

            generalRequest.header("Authorization", "bearer " + defaultClient.getAccessToken());

            GeneralResponse rtspUrlResponse = defaultClient.doAction(generalRequest, generalRequest.getResponseClass());

            JSON res = JSONUtil.parse(rtspUrlResponse.getResult());

            String url = res.getByPath("data.url", String.class);
            String token = res.getByPath("data.token", String.class);

            return url + "?token=" + token;
        });
    }

    public String getDeviceFirstUrl(ActionVideoInBo actionVideoInBo) {
        JSON json = viewDevice(actionVideoInBo);

        DeviceBean deviceBean = json.toBean(DeviceBean.class);

        //设备在线
        if (deviceBean.getIsOnline() == 1 && CollectionUtil.isNotEmpty(deviceBean.getUnits())) {
            List<DeviceChannelBean> channels = deviceBean.getUnits().get(0).getChannels();
            if (CollectionUtil.isNotEmpty(channels)) {
                actionVideoInBo.setCameraIndexCode(channels.get(0).getChannelCode());
                return getUrl(actionVideoInBo);
            }
        }
        throw new ComException("没有可用视频设备...");
    }

    public JSON viewDevice(ActionVideoInBo actionVideoInBo) {
        return UtilCatch.tryCatch(() -> {
            GeneralRequest generalRequest = new GeneralRequest("/evo-apigw/evo-brm/1.0.0/device/"+actionVideoInBo.getDeviceCode(), Method.GET);
            // 发起请求处理应答
            GeneralResponse generalResponse = defaultClient.doAction(generalRequest, generalRequest.getResponseClass());

            if (!generalResponse.isSuccess()) {
                throw new ComException("大华视频服务-获取设备详情失败！");
            }
            Result deviceBeanResult = JSONUtil.toBean(generalResponse.getResult(), Result.class);
            return JSONUtil.parse(deviceBeanResult.getData());
        });
    }

    private JSONObject configParams(ActionVideoInBo actionVideoInBo) {
        JSONObject params = JSONUtil.createObj()
                // channelId 视频通道编码
                .set("channelId", actionVideoInBo.getCameraIndexCode())
                // dataType 视频类型：1=视频
                .set("dataType", "1")
                // streamType 码流类型：1=主码流，2=辅码流
                .set("streamType", "1");

        if (!EnumStreamUrlProtocol.PROTOCOL_RTSP.equals(actionVideoInBo.getStreamUrlProtocol())) {
            params.set("type", actionVideoInBo.getStreamUrlProtocol().getProtocolName());
        }
        return JSONUtil.createObj().set("data", params);
    }

    private GeneralRequest generatorRequest(ActionVideoInBo actionVideoInBo) throws ClientException {
        switch (actionVideoInBo.getStreamUrlProtocol()) {
            case PROTOCOL_RTSP: return new GeneralRequest("/evo-apigw/admin/API/MTS/Video/StartVideo", Method.POST);
            case PROTOCOL_HLS: return new GeneralRequest("/evo-apigw/admin/API/video/stream/realtime", Method.POST);
            default: throw new ComException("大华逻辑执行异常，找不到对应的协议支持...");
        }
    }

    public static ToolDaHua me(String host, String username, String password, String clientId, String clientSecret) {
        return new ToolDaHua(UtilCatch.tryCatch(() -> new DefaultClient(host, username, password, clientId, clientSecret)));
    }

    public static void main(String[] args) throws ClientException {
        DefaultClient defaultClient = new DefaultClient("192.168.3.118", "system", "hmshxxb159", "fuminghuanbao-dahua", "a2520d3b-fabf-4db4-89ab-2a36fb106fff");
//        ToolDaHua me = ToolDaHua.me("192.168.3.118", "system", "hmshxxb159", "fuminghuanbao-dahua", "a2520d3b-fabf-4db4-89ab-2a36fb106fff");
        StaticLog.info("123456");
    }

}
